#include<iostream>
#include<unistd.h>
#include<pthread.h>
#include <ctime>


//线程的进程地址空间是共享的--测试代码
int gval = 100;
void* ThreadStart(void* args)
{
    while(true)
    {
        sleep(1);
        std::cout<<"new thread running...,gval = "<<gval<<std::endl;
    }
}
//线程的健壮性测试
// void* ThreadStart(void* args)
// {
//     while(true)
//     {
//         int x = rand() % 5;
//         std::cout<<"new thread running...,my pid = "<<getpid()<<": "<<x<<std::endl;
//         if(x == 0 )
//         {
//             int* ptr = nullptr;
//             *ptr = 10;//野指针
//         }
//         sleep(1);
//     }
// }
int main()
{
    //srand(time(nullptr));

    pthread_t tid1;
    pthread_create(&tid1,nullptr,ThreadStart,(void*)"new thread");
    
    pthread_t tid2;
    pthread_create(&tid2,nullptr,ThreadStart,(void*)"new thread");
    
    pthread_t tid3;
    pthread_create(&tid3,nullptr,ThreadStart,(void*)"new thread");
    
    pthread_t tid4;
    pthread_create(&tid4,nullptr,ThreadStart,(void*)"new thread");
    while(true)
    {
        sleep(1);
        std::cout<<"main thread running...,getpid = "<<getpid()<<"gval = "<<gval<<std::endl;
        ++gval;
    }
    return 0;
}